const cheerio = require('cheerio')
const superagent = require('superagent')
const router = require('koa-router')()
const Message = require('../dbs/modules/message')
const jwt = require('jsonwebtoken')

router.prefix('/blog')

let reptileList = []

// 首页文章接口
router.get('/articleList', async (ctx, next) => {
  let url = 'https://news.baidu.com/'
  await new Promise(function (resolve, reject) {
    superagent.get(url).end((err, res) => {
      let html = res.text,
        $ = cheerio.load(html, {
          decodeEntities: false
        })
      reptileList = [] // 每次请求清空数组 获取最新文章
      $("#pane-news ul li").each((index, item) => {
        let temp = {
          tit: $(item).text(),
          url: $(item).find('a').attr('href'),
          content: $(item).text(),
          author: '佚名',
          read: Math.ceil(Math.random() * 100),
          comment: Math.ceil(Math.random() * 100),
        }
        reptileList.push(temp)
        resolve('ok')
      })
    })
  }).then(res => {
    ctx.body = {
      reptileList,
      success: true
    }
  })
})

// 添加留言
router.post('/addMessage', async (ctx, next) => {
  const {
    message
  } = ctx.request.body
  let code
  let token = ctx.header.token
  // 校验是否登录
  if(!token) {
    ctx.body = {
      code: -1,
      success: false,
      msg: '用户未登录'
    }
    return false;
  }
  if (!message) {
    ctx.body = {
      code: -1,
      success: false,
      msg: '留言不能为空'
    }
    return false;
  }
  const msgdata = new Message({
    msg: message,
    author: '佚名',
    timeStamp: new Date().toLocaleString()
  })
  try {
    await msgdata.save()
    code = 0
  } catch (error) {
    code = -1
  }
  ctx.body = {
    code,
    success: true,
  }
})

// 获取留言
router.get('/getMessage', async (ctx, next) => {
  let code
  let totle = await Message.count(); //表总记录数
  let page = Number(ctx.query.page); //当前第几页
  let size = Number(ctx.query.size); //每页显示的记录条数
  const messageList = await Message.find().limit(size).skip((page - 1) * size)
  //是否还有更多
  let hasMore = totle - (page - 1) * size > size ? true : false;
  try {
    if (JSON.stringify(messageList) == '[]') {
      code = -2
    } else {
      code = 0
    }
  } catch (error) {
    code = -1
  }
  ctx.body = {
    messageList: messageList.reverse(),
    hasMore,
    totle,
    code,
    success: true
  }
})

module.exports = router
